package edu.zut.util;

import java.sql.*;

//jdbc操作模板
public class DBUtil {

    //驱动的加载注册
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    static final String URL = "jdbc:mysql://127.0.0.1:3306/ssm?characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
    static final String USER = "root";
    static final String PSW = "qwer1234";

    static Connection connection = null;
    static PreparedStatement statement = null;
    static ResultSet resultSet = null;
    /**
     * 数据库连接的获取
     * @return 数据库连接
     */
    public static Connection getConn(){
        try {
            connection = DriverManager.getConnection(URL, USER, PSW);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 查询的统一操作
     * @param sql sql语句
     * @param objs sql中需要填充的数据
     * @return 结果集
     */
    public static ResultSet query(String sql, Object... objs){
        connection = getConn();
        try {
            statement = connection.prepareStatement(sql);
            //判断是否需要往sql中填充数据
            if (null != objs && objs.length > 0){
                for (int i = 0; i < objs.length; i++) {
                    statement.setObject(i + 1,objs[i]);
                }
            }
            resultSet = statement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;
    }



    /**
     * 增删改统一操作   自行书写封装
     */
    public static int update(String sql, Object... objs){
        connection = getConn();
        int result = 0;
        try {
            statement = connection.prepareStatement(sql);
            //判断是否需要往sql中填充数据
            if (null != objs && objs.length > 0){
                for (int i = 0; i < objs.length; i++) {
                    statement.setObject(i + 1,objs[i]);
                }
            }
            result = statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            free();
        }
        return result;
    }

    /**
     * 关闭资源
     */
    public static void free(){
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != statement){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (null != connection){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }




}
